<template>
  <div class="p-8 overflow-y-auto font-mono flex-col flex gap-4">
    <Selector :selected="selected" @update:selected="(s) => (selected = s)" />
    <NDataTable :columns="columns" :data="data" :pagination="pagination" />
    <!-- <pre>{{ JSON.stringify(data, null, 2) }}</pre> -->
  </div>
</template>

<script setup>
import { computed, h, ref } from "vue";
import { NInput, NDataTable, NButton } from "naive-ui";
import { useRoute } from "vue-router";
import Selector from "@/components/Selector.vue";
import { rand } from "@vueuse/core";
import { round } from "lodash-es";

const route = useRoute();
const selected = ref(route.query.label || "S1");
const switchers = ['S1', 'S2', 'S3', 'S4']
const originData = ref({})
switchers.forEach((v, i) => {
  const prob1 = rand(1, 10) / 10
  const prob2 = 1 - prob1
  return originData.value[v] = [
    {
      id: 1,
      device: v,
      match: `10.0.0.${i * 2 + 1}/32`,
      action: "set _designate _nhop",
      port: 1,
      prob: round(prob1, 1),
    },
    {
      id: 2,
      device: v,
      match: `10.0.0.${i * 2 + 1}/32`,
      action: "set _designate _nhop",
      port: 2,
      prob: round(prob2, 1),
    },
    {
      id: 3,
      device: v,
      match: `10.0.0.${i * 2 + 2}/32`,
      action: "ipv4_ select _forward",
      port: 3,
      prob: 1,
    },
  ]
})

const data = computed(() => originData.value[selected.value])

const columns = [
  {
    title: "ID",
    key: "id",
    width: 64,
    render: custom_render("id"),
  },
  {
    title: "设备",
    key: "device",
    width: 128,
    render: custom_render("device"),
  },
  {
    title: "匹配参数",
    key: "match",
    width: 256,
    render: custom_render("match"),
  },
  {
    title: "Action entry(动作表项)",
    key: "action",
    render: custom_render("action"),
  },
  {
    title: "输出端口",
    key: "port",
    width: 96,
    render: custom_render("port"),
  },
  {
    title: "概率",
    key: "prob",
    width: 96,
    render: custom_render("prob"),
  },
  {
    title: "操作",
    key: "op",
    width: 96,
    render() {
      return h(
        NButton,
        {
          onClick(v) {
            alert("修改成功");
          },
          type: "primary",
          class: "text-white",
        },
        "修改"
      );
    },
  },
];

function custom_render(col) {
  return (row, index) => {
    return h(NInput, {
      value: row[col],
      onUpdateValue(v) {
        originData.value[selected.value][index][col] = v;
      },
    });
  };
}
</script>
